
import { Store } from 'vuex'
import { RootStateTypes } from '@/store/interface'
import { Session } from '@/utils/storage'

type savemap = {
  [key: string]: Function
}

const saveMap:savemap = {
  'user/SET_ACCOUNT' (state:RootStateTypes) {
    const account = state.user.account || null
    Session.set('account',account)
  },
  'user/SET_TOKEN' (state:RootStateTypes) {
    const token = state.user?.token || ''
    Session.set('token',token)
  },
  'user/SET_COOKIE' (state: RootStateTypes) {
    const cookie = state.user.cookie || ''
    Session.set('cookie',cookie)
  },
  'user/SET_AuthPageList' (state: RootStateTypes) {
    const cookie = state.user.cookie || ''
    Session.set('authPageList',cookie)
  },
  'user/SET_AuthBtnList' (state: RootStateTypes) {
    const cookie = state.user.cookie || ''
    Session.set('authBtnList',cookie)
  }
}

// 本地存储插件
export const localStoragePlugin = (store:Store<RootStateTypes>) => {
  // 当 store 初始化后调用
  store.subscribe(({ type }, state) => {
    if(!type.startsWith('user/')) return
    saveMap[type]&&saveMap[type](state)
  })
}
